package com.itheima.case2.service.impl;

import com.itheima.case2.dao.UserMapper;
import com.itheima.case2.pojo.po.User;
import com.itheima.case2.pojo.vo.AddUser;
import com.itheima.case2.pojo.vo.PageResult;
import com.itheima.case2.pojo.vo.QueryPageBean;
import com.itheima.case2.pojo.vo.UpdateUser;
import com.itheima.case2.service.UserService;
import com.itheima.case2.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {

    public PageResult selectByPage(QueryPageBean queryPageBean) {
        //1. 参数处理
            // 以前计算数据库索引, 现在不算 TODO:
//        queryPageBean.getOffset();
        //2. 数据库查询
        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.findUserByPage(queryPageBean);
        Long total = mapper.findUserTotal(queryPageBean);
        //3. 结果封装
        PageResult pageResult = new PageResult(total, list);
        session.close();
        return pageResult;
    }

    public void addUser(AddUser au) {

        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        //	I. 在t_user表中添加用户信息 (主键回填)
        mapper.addUser(au);
        //  II.  在t_user_role添加该用户的角色信息
        mapper.addRoleByUid(au.getId(),au.getRoleIds());
        session.close();
    }

    public void updateUser(UpdateUser uu) {

        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        //1). 修改t_user表
        mapper.updateUser(uu);
        //2). 修改t_user_role表 : 先删除再添加
        mapper.deleteRoleByUid(uu.getId());
        mapper.addRoleByUid(uu.getId(), uu.getRoleIds());

        session.close();
    }

    public void deleteUser(String uidStr) {
        SqlSession session = SqlSessionUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        int uid = Integer.parseInt(uidStr);
//        1). 因为外键约束的存在,先删除中间表中的数据 t_user_role
//        delete from t_user_role where user_id = ?;
        mapper.deleteRoleByUid(uid);
//        2). 再删除t_user
//        delete from t_user where id = ?;
        mapper.deleteUserById(uid);
        session.close();
    }
}
